import React, { useContext, useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import { Table,Popconfirm, Form, Space, Switch, DatePicker, TimePicker, Select, Card, Modal, Input, Button, Layout, Menu, Breadcrumb, Carousel, Row, Col, Divider } from 'antd';
import { AudioOutlined } from '@ant-design/icons';
import EditableTable from "../index";
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import axios from "../axios/axios";
import moment from "moment";
// import Home from './Home';
import ParticlesBg from 'particles-bg'
import './index.css'
import Particles from 'react-particles-js';

const { Search } = Input;
const { Meta } = Card;
const { Header, Content, Footer } = Layout;


const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

const EditableCell = ({
                          title,
                          editable,
                          children,
                          dataIndex,
                          record,
                          handleSave,
                          ...restProps
                      }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{
                    margin: 0,
                }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{
                    paddingRight: 24,
                }}
                onClick={toggleEdit}
            >
                {children}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};

export default class DeleteSearchResult extends React.Component {
    constructor(props) {
        super(props);
        this.columns = [
            {
                title: '标题',
                dataIndex: 'name',
                width: '20%',
                editable: true,
            },
            {
                title: '问卷类型',
                dataIndex: 'type',
            },
            {
                title: '创建时间',
                dataIndex: 'post',
                sorter: {
                    compare: (a, b) => new Date(a.post).getTime() - new Date(b.post).getTime(),
                },

            },
            {
                title: '删除时间',
                dataIndex: 'deletetime',
                sorter: {
                    compare: (a, b) => new Date(a.deletetime).getTime() - new Date(b.deletetime).getTime(),
                },
                //两个排序方向
                sortDirections: ['descend', 'ascend'],
                //默认排序
                defaultSortOrder: 'descend',
            },
            {
                title: '回收量',
                dataIndex: 'ret',
                sorter: {
                    compare: (a, b) => a.ret - b.ret,
                },
            },
            {
                title: '预览',
                dataIndex: 're',
                render: (_, record) => (
                    <Space size="middle">
                        <a onClick={() => this.handleRelook(record.key)}>预览</a>
                    </Space>
                ),
            },
            {
                title: '复原',
                dataIndex: 'operation',
                render: (_, record) =>
                    this.state.dataSource.length >= 1 ? (
                        <Popconfirm title="确认复原?" onConfirm={() => this.handleReform(record.key)}>
                            <a>复原</a>
                        </Popconfirm>
                    ) : null,
            },
            {
                title: '永久删除',
                dataIndex: 'perdelete',
                render: (_, record) =>
                    this.state.dataSource.length >= 1 ? (
                        <Popconfirm title="确认永久删除?" onConfirm={() => this.perDelete(record.key)}>
                            <a>永久删除</a>
                        </Popconfirm>
                    ) : null,
            },

        ];
        this.state = {
            dataSource: [
                /*{
                    key: '0',
                    name: 'aa',
                    post: '2021-06-02',
                    create: '2021-06-01',
                    ret: '100'
                },
                {
                    key: '1',
                    name: 'bb',
                    post: '2021-05-09',
                    create: '2021-05-04',
                    ret: '200'
                },*/
            ],
            count: 0,
        };
    }

    componentWillMount() {
        const _this=this;
        const changeDate=(value)=>{
            return moment(value).format('YYYY-MM-DD HH:mm:ss');
        }
        axios.get('/ques/searchDeleted', {params: {keyword:this.props.location.state.keyword}})
            .then(function (response) {
                console.log(response.data.data)

                let arr=response.data.data
                for(var i=0;i<arr.length;i++){
                    const { count,dataSource } = _this.state;
                    const newData ={
                        key:count,
                        name: arr[i].title,
                        num: arr[i].q_id,
                        state: arr[i].state,
                        post: changeDate(arr[i].release_time),
                        ret: arr[i].recover_num,
                        deletetime:changeDate(arr[i].delete_time),
                        type:arr[i].q_type
                    }
                    _this.setState({
                        dataSource: [...dataSource, newData],
                        count: count + 1,
                    })
                }

            })
    }

    handleRelook= (key) =>{
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        this.props.history.push({pathname:"/preview/", state : value});
    }
    handleReform= (key) =>{
        const dataSource = [...this.state.dataSource];

        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].stprop;

        axios.post('/ques/unDelete',{"qid" : value}).then(
            function (response){console.log("response:",response)}).catch(err=>console.log(err))

        dataSource.splice(key,1)
        for(var i=0;i<dataSource.length;i++){
            dataSource[i].key=i;
        }
        this.setState({
            dataSource:dataSource
        })
    }
    perDelete= (key) =>{
        const dataSource = [...this.state.dataSource];
        let value=this.state.dataSource[key]&&this.state.dataSource[key].num;
        let tmp=this.state.dataSource[key]&&this.state.dataSource[key].stprop;
        axios.post('/ques/delQues',{"qid" : value}).then(
            function (response){console.log("response:",response)}).catch(err=>console.log(err))
        dataSource.splice(key,1)
        for(var i=0;i<dataSource.length;i++){
            dataSource[i].key=i;
        }
        this.setState({
            dataSource:dataSource
        })
    }
    render() {
        const { dataSource } = this.state;
        const components = {
            body: {
                row: EditableRow,
                cell: EditableCell,
            },
        };
        const columns = this.columns.map((col) => {
            if (!col.editable) {
                return col;
            }

            return {
                ...col,
                onCell: (record) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    handleSave: this.handleSave,
                }),
            };
        });
        return (
            <>
                <div>
                <Particles
                    style={{ position: "fixed", top:0}}
                    height="95%"
                    width="100%"
                    params={{
                        particles: {
                        color: {
                            value: "#000000"
                        },
                        line_linked: {
                            color: {
                            value: "#1E90FF"
                            }
                        },
                        number: {
                            value: 50
                        },
                        size: {
                            value: 3.25
                        }
                        }
                    }}
                />
                {/* <ParticlesBg color="#ff0000" num={400} type="lines" bg={true} color='white'/> */}
                {/* <ParticlesBg type="random" bg={true}/> */}
                <Layout className="layout">
                    <Header>
                        <div className="logo" />
                        <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}></Menu>
                    </Header>
                    <Content className="null" style={{ margin: '24px 16px 0', overflow: 'initial',padding: '0 50px' }}>
                    <div>
                <Link to="/delete">
                    <Button
                        type="primary"
                        style={{
                            marginBottom: 16,
                        }}
                        onClick={this.handleback}
                    >
                        返回
                    </Button>
                </Link>
                <Table
                    components={components}
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={dataSource}
                    columns={columns}
                />
            </div>
                    </Content>
                    <Footer style={{ textAlign: 'center' }}>~~~欢迎来到问卷星球~~~</Footer> */}
                </Layout> 
            </div>
            </>

        );
    }

}
